import { useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import MatchHistory from './MatchHistory'
import { Player, Match } from '../types/dota'

interface PlayerProfileProps {
  player: Player
  matches: Match[]
  onLoadMatches: (accountId: string) => Promise<void>
  onMatchClick?: (matchId: number) => void
  onBackToSearch?: () => void
}

export default function PlayerProfile({ player, matches, onLoadMatches, onMatchClick, onBackToSearch }: PlayerProfileProps) {
  const [loadingMatches, setLoadingMatches] = useState(false)
  // const [matchesLoaded, setMatchesLoaded] = useState(false)

  // 调试日志：检查player对象的数据结构
  console.log('PlayerProfile - player data:', player)
  console.log('PlayerProfile - personaname:', player.profile?.personaname)
  console.log('PlayerProfile - account_id:', player.profile?.account_id)
  console.log('PlayerProfile - avatarfull:', player.profile?.avatarfull)

  const getRankTier = (rankTier?: number): { name: string; color: string; star?: number } => {
    if (!rankTier) return { name: 'Unranked', color: 'bg-gray-500' }
    
    const tier = Math.floor(rankTier / 10)
    const star = rankTier % 10
    
    const ranks = [
      { name: 'Herald', color: 'bg-gray-600' },
      { name: 'Guardian', color: 'bg-green-600' },
      { name: 'Crusader', color: 'bg-yellow-600' },
      { name: 'Archon', color: 'bg-orange-600' },
      { name: 'Legend', color: 'bg-blue-600' },
      { name: 'Ancient', color: 'bg-purple-600' },
      { name: 'Divine', color: 'bg-pink-600' },
      { name: 'Immortal', color: 'bg-red-600' }
    ]
    
    const rank = ranks[tier - 1] || ranks[0]
    return { ...rank, star }
  }

  const formatLastLogin = (lastLogin?: string) => {
    if (!lastLogin) return 'Unknown'
    const date = new Date(lastLogin)
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
  }

  const loadMatches = async () => {
    setLoadingMatches(true)
    try {
      await onLoadMatches(player.profile.account_id.toString())
      // setMatchesLoaded(true)
    } catch (error) {
      console.error('Failed to load matches:', error)
    } finally {
      setLoadingMatches(false)
    }
  }

  const rank = getRankTier(player.rank_tier)

  return (
    <div className="space-y-6">
      <Card className="modern-card gradient-border">
        <CardHeader className="pb-6">
          <div className="flex items-start space-x-6">
            <div className="relative shine-effect">
              <img
                src={player.profile?.avatarfull || ''}
                alt={player.profile?.personaname}
                className="w-24 h-24 rounded-xl border-2 border-border object-cover"
                onLoad={(e) => {
                  console.log('Image loaded successfully:', (e.target as HTMLImageElement).src)
                }}
                onError={(e) => {
                  console.log('Image failed to load:', (e.target as HTMLImageElement).src)
                  const target = e.target as HTMLImageElement
                  if (!target.src.includes(''
                  }
                }}
              />
            </div>
            <div className="flex-1 space-y-3">
              <div>
                <CardTitle className="text-2xl font-bold text-foreground mb-2">
                  {player.profile?.personaname}
                </CardTitle>
                <CardDescription className="text-base text-muted-foreground">
                  Account ID: {player.profile?.account_id}
                </CardDescription>
              </div>
              
              <div className="flex flex-wrap gap-3">
                <Badge 
                  className={`${rank.color} text-white px-3 py-1 text-sm font-medium`}
                >
                  {rank.name} {rank.star && `★${rank.star}`}
                </Badge>
                
                {player.leaderboard_rank && (
                  <Badge className="bg-gradient-to-r from-yellow-500 to-orange-500 text-white px-3 py-1 text-sm font-medium">
                    Leaderboard #{player.leaderboard_rank}
                  </Badge>
                )}
              </div>
            </div>
          </div>
        </CardHeader>
        
        <CardContent className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="stats-card">
              <div className="text-sm font-medium text-muted-foreground mb-1">Rank</div>
              <div className="text-lg font-bold text-foreground">
                {rank.name} {rank.star && `★${rank.star}`}
              </div>
            </div>
            
            {player.leaderboard_rank && (
              <div className="stats-card">
                <div className="text-sm font-medium text-muted-foreground mb-1">Leaderboard</div>
                <div className="text-lg font-bold text-foreground">
                  #{player.leaderboard_rank}
                </div>
              </div>
            )}
            
            <div className="stats-card">
              <div className="text-sm font-medium text-muted-foreground mb-1">Last Login</div>
              <div className="text-sm text-foreground">
                {formatLastLogin(player.profile?.last_login)}
              </div>
            </div>
          </div>
          
          <Separator />
          
          <div className="flex flex-col sm:flex-row gap-3">
            <Button
              onClick={loadMatches}
              disabled={loadingMatches}
              className="modern-button-primary flex-1"
            >
              {loadingMatches ? (
                <div className="flex items-center space-x-2">
                  <div className="loading-spinner w-4 h-4"></div>
                  <span>Loading Matches...</span>
                </div>
              ) : (
                <div className="flex items-center space-x-2">
                  <span>📊</span>
                  <span>Load Recent Matches</span>
                </div>
              )}
            </Button>
            
            <Button
              onClick={() => window.open(player.profile?.profileurl, '_blank')}
              variant="outline"
              className="modern-button-secondary flex-1"
            >
              <div className="flex items-center space-x-2">
                <span>🔗</span>
                <span>View Steam Profile</span>
              </div>
            </Button>
            
            {onBackToSearch && (
              <Button
                onClick={onBackToSearch}
                variant="outline"
                className="modern-button-secondary flex-1"
              >
                <div className="flex items-center space-x-2">
                  <span>🔍</span>
                  <span>Back to Search</span>
                </div>
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {matches.length > 0 && (
        <MatchHistory matches={matches} onMatchClick={onMatchClick} />
      )}
    </div>
  )
}